package pers.vic.basics.leetcode;

/**
 * @author Vic.xu
 * @description: 81. 搜索旋转排序数组 II  <a href="https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/">81. 搜索旋转排序数组 II</a>
 * @date: 2021/1/19 0019 8:27
 * @see J0033_M_search
 */
public class J0081_M_Search {
    /*
    假设按照升序排序的数组在预先未知的某个点上进行了旋转。
    ( 例如，数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。
     编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true，否则返回 false。
     和33题的区别是本题中的nums可能有重复项
     */

    /**
     * 看到二分法 就有点头疼，何况还要加上其他的条件
     *
     *<a href = "https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/solution/yi-wen-dai-ni-gao-ding-er-fen-sou-suo-ji-ki52/">二分法详解</a>
     * 1. 找到中间值  ，判断那边是有序的
     * 2. 有序的部分二分查找，无序的重复上述判断
     * 3. 重复值的判断
     */
    public static boolean search(int[] nums, int target) {
        int len = nums.length;
        if (len == 0) {
            return false;
        }

        if (len == 1) {
            return target == nums[0];
        }
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                return true;
            }
            //右边有序
            if (nums[mid] < nums[right]) {
                //且在右侧
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
                //左边有序
            } else if (nums[mid] > nums[right]) {
                //且在左侧
                if (target < nums[mid] && target >= nums[left]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
                //中间和右侧相等,有重复
            } else {
                right--;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = {2,5,6,0,0,1,2};
        int target = 0;
        System.out.println(search(nums, target));

        nums = new int[]{2,5,6,0,0,1,2};
        target = 3;
        System.out.println(search(nums, target));

    }

}
